package com.element.security.server.global.code;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;

/**
 * @auther zhangwj
 * @date 2021/12/4 下午11:10
 */
public class CodeAuthenticationProvider implements AuthenticationProvider {

    private ClientDetailsService clientDetailsService;

    public CodeAuthenticationProvider(ClientDetailsService clientDetailsService) {
        this.clientDetailsService = clientDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        CodeAuthenticationToken authenticationToken = (CodeAuthenticationToken) authentication;
        String appKey = (String) authenticationToken.getPrincipal();
        String appSecret = (String) authenticationToken.getCredentials();
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(appKey);
        if (null == clientDetails) {
            throw new ClientRegistrationException("clientDetails is null");
        }
        CodeAuthenticationToken codeAuthenticationToken = new CodeAuthenticationToken(clientDetails, appSecret, null);
        codeAuthenticationToken.setDetails(authenticationToken.getDetails());
        return codeAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
